package com.huluobo.h3kotlinproject.cart

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.EnvUtils
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.h3kotlinproject.R
import com.huluobo.h3kotlinproject.base.BaseMVVMFragment
import com.huluobo.h3kotlinproject.databinding.FragmentCartBinding
import com.huluobo.h3kotlinproject.pay.PayResult
import com.huluobo.h3kotlinproject.pay.util.OrderInfoUtil2_0


class CartFragment : BaseMVVMFragment<FragmentCartBinding>() {

    private lateinit var cartViewModel: CartViewModel

    private lateinit var cartAdapter: CartAdapter

    private val cartList = mutableListOf<CartBean>()
    override fun getLayoutId(): Int = R.layout.fragment_cart

    private var hasSelectGoods = false


    override fun initData() {
        cartViewModel = ViewModelProvider(requireActivity())[CartViewModel::class.java]
        cartViewModel.getCartList()

        cartViewModel.getCartListSuccess.observe(this) {
            cartList.clear()
            cartList.addAll(it.data)
            cartAdapter.notifyDataSetChanged()
        }

        cartViewModel.deleteCartSuccess.observe(this) {
            ToastUtils.showLong("删除成功")
        }

        cartViewModel.addCartSuccess.observe(this) {
            Log.i("TagA", "购物车数量+1")
        }

        cartViewModel.removeCartSuccess.observe(this) {
            Log.i("TagA", "购物车数量-1")
        }
    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        cartAdapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = cartAdapter

        //全选按钮点击事件
        dataBinding.cartCbSelectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            if (cartList.size > 0) {
                cartList.map {
                    //遍历list中每一个值,可以替换为循环
                    it.selected = isChecked
                }

//                for (position in 0 until cartList.size) {
//                    (cartAdapter.getViewByPosition(position, R.id.cart_item_cb) as CheckBox).isChecked = isChecked
//                }

//                for ( it in cartList){
//                    it.selected = isChecked
//                }
                cartAdapter.notifyDataSetChanged()

                totalPrice()
            }
        }

        cartAdapter.addChildClickViewIds(
            R.id.cart_item_iv_add,
            R.id.cart_item_iv_reduce,
            R.id.cart_item_iv_delete,
            R.id.cart_item_cb
        )

        //操作adapter中每个item 的点击事件
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.cart_item_iv_add -> {
                    cartList[position].count += 1
                    cartViewModel.addOneCart(1, cartList[position].goods_id)
                    // 局部刷新一个item的数量
                    (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                        "${cartList[position].count}"
                }

                R.id.cart_item_iv_reduce -> {
                    if (cartList[position].count > 1) {
                        cartList[position].count -= 1
                        cartViewModel.removeOneCart(-1, cartList[position].goods_id)
                        // 局部刷新一个item的数量
                        (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                            "${cartList[position].count}"
                    }
                }

                R.id.cart_item_iv_delete -> {
                    cartViewModel.deleteCart(cartList[position].id.toString())
                    cartList.removeAt(position)
                    adapter.notifyItemRemoved(position)//局部删除一个item
                }

                R.id.cart_item_cb -> {
                    cartList[position].selected = !cartList[position].selected
                    (adapter.getViewByPosition(position, R.id.cart_item_cb) as CheckBox).isChecked =
                        cartList[position].selected
                }
            }
            totalPrice()
        }

        totalPrice()
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX)

        dataBinding.cartTvPay.setOnClickListener {
            pay("10000")
        }
    }

    //计算总价
    private fun totalPrice() {
        var totalPrice = 0
        //循环list,如果其中有一项是false就都是false,否则就是true
        val checkSet = mutableSetOf<Boolean>()
        cartList.forEach {
            if (it.selected) {
                totalPrice += it.goods_default_price * it.count
            }
            checkSet.add(it.selected)//将每一个item中的是否被选中放到set中
        }

        //检查set中是否有false,有就代表没有全选,全是true,就代表全选
        dataBinding.cartCbSelectAll.isChecked = false !in checkSet


        dataBinding.cartTvTotalPrice.text = "总价:${totalPrice}"
    }
//    var context: Context? = null
//    fun MyPay(context: Context?) {
//        this.context = context
//    }

    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    val APPID = "2021000122688185"

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    val PID = ""

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    val TARGET_ID = ""

    /**
     * pkcs8 格式的商户私钥。
     *
     *
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     *
     *
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    val RSA2_PRIVATE =
        "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDLUPyKOCQh2Ii5BOVlpe6td9JQxieaSpGvTykHN6cWJqTmQWz/cKxYPnyjb0VTY/yzJ/kJwovtIjRNNqa49kgrYTcOVWVhURsUq54sDzleS8hD4Qr8yqvO9UZ/Gh3gqRkanKW8cyeHUZScz+jl9A5q4MUXsV04UfrwZF2ZMN38++kjOQnJ/N5c5sqlFmYMXA+HPtVpxhdiFPxyV1/lj6AmRiG67VvSWLrlYyee/2kUZlAnHoHpR7dew4332gkjs1Iak98tYCUvIQCHb7Vg591z/nT8wTf6SIbM9kdqnAAL9gsMke87XK3l/OuOgwnRR+64XDMz0y7V8aoY3X4IfNITAgMBAAECggEAGiMSJA6tjnBQu0BG4TdgpIo3zkx7ANm/OsM5agUchLt5DWSxx3DLpxh5W2VNizfaX4mu+TM6W8S+5oI1EqgOhQ0dT8lonAcaLSEW12EppdamKxu+FttTFOrxIhvQZXY3lPU4VS6UkU/KhBIyRYWHaPP2QmJ5smjPkqHEapIep4vcASBvxm8sLAorR0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 1
    private val SDK_AUTH_FLAG = 2

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        @Suppress("unused")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show()
                    }
                }

                else -> {}
            }
        }
    }

    /**
     * 支付宝支付业务示例
     */
    fun pay(money: String?) {
        if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE)) {
            return
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        val rsa2 = RSA2_PRIVATE.length > 0
        val params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, money)
        val orderParam = OrderInfoUtil2_0.buildOrderParam(params)
        val privateKey = if (rsa2) RSA2_PRIVATE else RSA_PRIVATE
        val sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2)
        val orderInfo = "$orderParam&$sign"
        val payRunnable = Runnable {
            val alipay = PayTask(context as Activity?)
            val result = alipay.payV2(orderInfo, true)
            Log.i("msp", result.toString())
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

//    fun dddd(view: View?, money: String?) {
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX)
//        pay(view, money)
//    }
}